//
//  ByBlueToothListVC.m
//  laserdevice_ios
//
//  Created by pro on 16/12/8.
//  Copyright © 2016年 com.itboye. All rights reserved.
//

#import "ByBlueToothListVC.h"

#define channelOnPeropherList @"peripheralList"


// 蓝牙库和sdk
#import <CoreBluetooth/CoreBluetooth.h>
#import "BabyBluetooth.h"

#import "ByBlueToothHandleModel.h"

// cell
#import "ByBlueToothListCell.h"

@interface ByBlueToothListVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *table;
@end

@implementation ByBlueToothListVC
{
    NSMutableArray *peripherals;
    NSMutableArray *peripheralsAD;
    BabyBluetooth *baby;
}

static ByBlueToothListVC *instance;

//+ (ByBlueToothListVC *)shareInstance {
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        instance = [[ByBlueToothListVC alloc] init];
//    });
//    return instance;
//}
//+ (id)allocWithZone:(struct _NSZone *)zone {
//    
//    if (instance == nil) {
//        instance = [super allocWithZone:zone];
//    }
//    return instance;
//}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = STRING(@"lanyalianji");
    [self addLeftBackBarButtonItem];
    
    [self createTableView];
    
    // 初始化其他数据 init other
    peripherals = [[NSMutableArray alloc] init];
    peripheralsAD = [[NSMutableArray alloc] init];
    
    // 初始化BabyBluetooth 蓝牙库
    baby = [BabyBluetooth shareBabyBluetooth];
    // 设置蓝牙委托
    [self babyDelegate];

}


-(void)viewDidAppear:(BOOL)animated{
    NSLog(@"viewDidAppear");
    
    baby.channel(channelOnPeropherList);

    // 停止之前的连接
    [baby cancelAllPeripheralsConnection];
    [ByBlueToothHandleModel shareInstance].characteristic = nil;
    
    // 设置委托后直接可以使用，无需等待CBCentralManagerStatePoweredOn状态。
    baby.scanForPeripherals().begin();
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [baby cancelScan];
    [ByCoreToolAlert hideHud];
}

#pragma mark -蓝牙配置和操作
//蓝牙网关初始化和委托方法设置
-(void)babyDelegate{


    __weak typeof(self) weakSelf = self;
    [baby setBlockOnCentralManagerDidUpdateStateAtChannel:channelOnPeropherList block:^(CBCentralManager *central) {
        if (central.state == CBCentralManagerStatePoweredOn) {
            [ByCoreToolAlert showOnlyText:STRING(@"kaishisaomiao")];
        }
    }];
    
    //设置扫描到设备的委托
    [baby setBlockOnDiscoverToPeripheralsAtChannel:channelOnPeropherList block:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        NSLog(@"搜索到了设备:%@",peripheral.name);
        [weakSelf insertTableView:peripheral advertisementData:advertisementData];
    }];
    
//    //设置发现设备的Services的委托
//    [baby setBlockOnDiscoverServices:^(CBPeripheral *peripheral, NSError *error) {
//        for (CBService *service in peripheral.services) {
//            NSLog(@"搜索到服务:%@",service.UUID.UUIDString);
//        }
//        //找到cell并修改detaisText
//        for (int i=0;i<peripherals.count;i++) {
//            UITableViewCell *cell = [weakSelf.table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
//            if ([cell.textLabel.text isEqualToString:peripheral.name]) {
//                cell.detailTextLabel.text = [NSString stringWithFormat:@"%lu个service",(unsigned long)peripheral.services.count];
//            }
//        }
//    }];
//    //设置发现设service的Characteristics的委托
//    [baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
//        NSLog(@"===service name:%@",service.UUID);
//        for (CBCharacteristic *c in service.characteristics) {
//            NSLog(@"charateristic name is :%@",c.UUID);
//        }
//    }];
//    //设置读取characteristics的委托
//    [baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
//        NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);
//    }];
//    //设置发现characteristics的descriptors的委托
//    [baby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
//        NSLog(@"===characteristic name:%@",characteristic.service.UUID);
//        for (CBDescriptor *d in characteristic.descriptors) {
//            NSLog(@"CBDescriptor name is :%@",d.UUID);
//        }
//    }];
//    //设置读取Descriptor的委托
//    [baby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
//        NSLog(@"Descriptor name:%@ value is:%@",descriptor.characteristic.UUID, descriptor.value);
//    }];
//    
//    
    //设置查找设备的过滤器
    [baby setFilterOnDiscoverPeripheralsAtChannel:channelOnPeropherList filter:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        
        //最常用的场景是查找某一个前缀开头的设备
        //        if ([peripheralName hasPrefix:@"Pxxxx"] ) {
        //            return YES;
        //        }
        //        return NO;
        
        //设置查找规则是名称大于0 ， the search rule is peripheral.name length > 0
        if (peripheralName.length >0) {
            return YES;
        }
        return NO;
    }];
//
//    
//    [baby setBlockOnCancelAllPeripheralsConnectionBlock:^(CBCentralManager *centralManager) {
//        NSLog(@"setBlockOnCancelAllPeripheralsConnectionBlock");
//    }];
//    
//    [baby setBlockOnCancelScanBlock:^(CBCentralManager *centralManager) {
//        NSLog(@"setBlockOnCancelScanBlock");
//    }];
    
    //示例:
    //扫描选项->CBCentralManagerScanOptionAllowDuplicatesKey:忽略同一个Peripheral端的多个发现事件被聚合成一个发现事件
    NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
    /*连接选项->
     CBConnectPeripheralOptionNotifyOnConnectionKey :当应用挂起时，如果有一个连接成功时，如果我们想要系统为指定的peripheral显示一个提示时，就使用这个key值。
     CBConnectPeripheralOptionNotifyOnDisconnectionKey :当应用挂起时，如果连接断开时，如果我们想要系统为指定的peripheral显示一个断开连接的提示时，就使用这个key值。
     CBConnectPeripheralOptionNotifyOnNotificationKey:
     当应用挂起时，使用该key值表示只要接收到给定peripheral端的通知就显示一个提
     */
    NSDictionary *connectOptions = @{CBConnectPeripheralOptionNotifyOnConnectionKey:@YES,
                                     CBConnectPeripheralOptionNotifyOnDisconnectionKey:@YES,
                                     CBConnectPeripheralOptionNotifyOnNotificationKey:@YES};
    
    //连接设备->
//    [baby setBabyOptionsWithScanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:connectOptions scanForPeripheralsWithServices:nil discoverWithServices:nil discoverWithCharacteristics:nil];
}

//插入table数据
-(void)insertTableView:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData{
    if(![peripherals containsObject:peripheral]) {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:peripherals.count inSection:0];
        [indexPaths addObject:indexPath];
        [peripherals addObject:peripheral];
        [peripheralsAD addObject:advertisementData];
        [self.table insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}


#pragma mark - 创建视图
// 创建表视图
- (void)createTableView {
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    self.table.backgroundColor = TABLE_COLOR;
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.tableFooterView = [UIView new];
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return peripherals.count;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ByBlueToothListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    CBPeripheral *peripheral = [peripherals objectAtIndex:indexPath.row];
    NSDictionary *ad = [peripheralsAD objectAtIndex:indexPath.row];
    
    if (!cell) {
        cell = [[ByBlueToothListCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    //peripheral的显示名称,优先用kCBAdvDataLocalName的定义，若没有再使用peripheral name
    NSString *localName;
    if ([ad objectForKey:@"kCBAdvDataLocalName"]) {
        localName = [NSString stringWithFormat:@"%@",[ad objectForKey:@"kCBAdvDataLocalName"]];
    }else{
        localName = peripheral.name;
    }
    
//    cell.textLabel.text = localName;
    cell.name = localName;
    //信号和服务
//    cell.detailTextLabel.text = @"读取中...";
//    //找到cell并修改detaisText
//    NSArray *serviceUUIDs = [ad objectForKey:@"kCBAdvDataServiceUUIDs"];
//    if (serviceUUIDs) {
//        cell.detailTextLabel.text = [NSString stringWithFormat:@"%lu个service",(unsigned long)serviceUUIDs.count];
//    }else{
//        cell.detailTextLabel.text = [NSString stringWithFormat:@"0个service"];
//    }
    
    //次线程读取RSSI和服务数量
    
    cell.backAction = ^ {
        
        [baby cancelScan];
        
        ByBlueToothHandleModel *handle = [ByBlueToothHandleModel shareInstance];
        handle.currPeripheral = [peripherals objectAtIndex:indexPath.row];
        handle.baby = self->baby;
        [handle.baby AutoReconnect:handle.currPeripheral];
        handle.baby.channel(channelOnPeropheralView);

//        [handle babyDelegate];
        [handle babyDelegateTest];

        [handle connectPeripheral];
        [handle setSuccessBlock:^{
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    };
    
    return cell;
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    [baby cancelScan];
//
//    ByBlueToothHandleModel *handle = [ByBlueToothHandleModel shareInstance];
//    handle.currPeripheral = [peripherals objectAtIndex:indexPath.row];
//    handle.baby = self->baby;
//    [handle babyDelegate];
//    [handle connectPeripheral];
//    [handle setSuccessBlock:^{
//        [self dismissViewControllerAnimated:YES completion:nil];
//    }];
}




@end
